
from django.db import models
from django.contrib.auth import get_user_model
from apps.project.models import ProjectModel
import uuid

User = get_user_model()

class ChatSessionModel(models.Model):
    """聊天会话模型"""
    STATUS_CHOICES = [
        ('active', '活跃'),
        ('finished', '已完成'),
        ('error', '错误'),
    ]
    
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    project = models.ForeignKey(ProjectModel, on_delete=models.CASCADE, related_name="chat_sessions", verbose_name="关联项目")
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="用户")
    title = models.CharField(max_length=255, verbose_name="会话标题")
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='active', verbose_name="状态")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    
    class Meta:
        db_table = "chat_session"
        ordering = ["-updated_at"]
        verbose_name = "聊天会话"
        verbose_name_plural = "聊天会话"

    def __str__(self):
        return self.title


class ChatMessageModel(models.Model):
    """聊天消息模型"""
    ROLE_CHOICES = [
        ('user', '用户'),
        ('assistant', 'AI助手'),
        ('system', '系统'),
    ]
    
    STATUS_CHOICES = [
        ('pending', '等待中'),
        ('processing', '处理中'),
        ('completed', '已完成'),
        ('error', '错误'),
    ]
    
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    session = models.ForeignKey(ChatSessionModel, on_delete=models.CASCADE, related_name="messages", verbose_name="会话")
    role = models.CharField(max_length=20, choices=ROLE_CHOICES, verbose_name="角色")
    content = models.TextField(verbose_name="消息内容")
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='completed', verbose_name="状态")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    
    # AI 生成的 markdown 相关
    generated_markdown = models.TextField(blank=True, null=True, verbose_name="生成的markdown")
    token_usage = models.JSONField(default=dict, blank=True, verbose_name="Token使用情况")
    
    class Meta:
        db_table = "chat_message"
        ordering = ["created_at"]
        verbose_name = "聊天消息"
        verbose_name_plural = "聊天消息"

    def __str__(self):
        return f"{self.session.title} - {self.role}: {self.content[:50]}"
